package com.healthdata.service.impl;

import com.healthdata.entity.HospitalCost;
import com.healthdata.dao.HospitalCostMapper;
import com.healthdata.service.HospitalCostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HospitalCostServiceImpl implements HospitalCostService {

    @Autowired
    private HospitalCostMapper hospitalCostMapper; // 变量名改为Mapper更合适

    @Override
    public Map<String, Object> getHospitalCostChartData() {
        // 查询所有年份的数据 - 使用selectList(null)查询所有记录
        List<HospitalCost> allCosts = hospitalCostMapper.selectList(null);

        // 构建返回数据
        Map<String, Object> result = new HashMap<>();

        // 年份标签
        List<String> years = Arrays.asList("2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022");
        result.put("labels", years.stream().map(year -> year + "年  ").collect(Collectors.toList()));

        // 构建数据集
        Map<String, List<Double>> dataset = new HashMap<>();
        dataset.put("total", getCostDataByLevel("医院合计", years, allCosts));
        dataset.put("committee", getCostDataByLevel("委属", years, allCosts));
        dataset.put("province", getCostDataByLevel("省属", years, allCosts));
        dataset.put("prefectureLevel", getCostDataByLevel("地级市属", years, allCosts));
        dataset.put("countyLevel", getCostDataByLevel("县级市属", years, allCosts));
        dataset.put("county", getCostDataByLevel("县属", years, allCosts));

        result.put("dataset", dataset);

        return result;
    }

    private List<Double> getCostDataByLevel(String level, List<String> years, List<HospitalCost> allCosts) {
        return years.stream()
                .map(yearStr -> {
                    int year = Integer.parseInt(yearStr);
                    return allCosts.stream()
                            .filter(cost -> cost.getLevel().equals(level) && cost.getYear() == year)
                            .findFirst()
                            .map(HospitalCost::getHospitalTotalCost)
                            .orElse(0.0);
                })
                .collect(Collectors.toList());
    }
}
